
from string import Template
import requests
import yaml
import logging
from Api_test.api import login_api

import os


class BaseApi:

    # 清理已有 handlers
    root_logger = logging.getLogger()
    for h in root_logger.handlers[:]:
        root_logger.removeHandler(h)
    logging.basicConfig(level=logging.INFO)

    #适配linux和windows的文件路径，要不在linux上执行不了
    # env = yaml.safe_load(open('E:/daofeng_api/pytest-allure-api-test/Api_test/data/env.yaml'))
    env = yaml.safe_load(open(os.path.dirname(os.path.dirname(__file__)) + '/data/env.yaml'))

    # @classmethod
    # def send(cls, data: dict):
    #     #替换
    #     data['api'] = cls.env['testing_studio'][cls.env['default']] + str(data['api'])
    #     print(data['headers'])
    #     r = requests.request(method=data['method'], url=data['api'], headers=data['headers'], params=data['params'])
    #     return r

    @classmethod
    def template(cls, po_path, key, token, **kwargs):
        '''
        yaml文件变量替换
        :return:
        '''

        #todo：如果yaml文件里有新的变量需要处理
        data = {'token': token,
                'headers': None,
                'order_id': login_api.order_id
                }

        with open(po_path, encoding="utf-8") as f:
            rw = Template(f.read()).substitute(data)
            re = yaml.safe_load(rw)
            rq = re[key]
            # print('rqqqqqqqqq', rq)

            method = rq['method']
            api = cls.env['testing_studio'][cls.env['default']] + rq['api']
            headers = rq['headers']
            params = rq['params']
            api_name = rq['name']
            logging.info(rq)

            r = requests.request(method=method, url=api, headers=headers, params=params)

            res = r.json()
            logging.info('ressssssssss', res)
            #todo:可以在这个方法里面定义提取变量（如order_id）的方法
            # print('req', r.status_code)
            assert r.status_code == 200
            return res

    @classmethod
    def get_token(cls):
            data = {
                'method': 'post',
                'api': '/pw/app/api/v2/mobileLogin.json',
                'headers': None,
                'params':
                    {
                        'password': '',
                        'source': '301',
                        'area_num': '86',
                        'mobile': '18538285467',
                        'registration_JGID': '1104a897927dd7c9e39',
                        'message_code': 9999
                    }
            }

            data['api'] = cls.env['testing_studio'][cls.env['default']] + str(data['api'])
            r = requests.request(method=data['method'], url=data['api'], headers=data['headers'], params=data['params']).json()
            return r['data']['token']






